package love.yuanmengrobot.als.business.dao.impl;

/*
 *   @Studio:CHJY · 源梦科技
 *   @Author:HuangHongTao
 *   @Ide:IntelliJ IDEA
 *   @Creation time:2021/5/31 10:24
 */

import love.yuanmengrobot.als.utilPublic.DQL;
import love.yuanmengrobot.als.utilPublic.JdbcUtil;
import love.yuanmengrobot.als.utilPublic.SqlString;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class StudentNotCourseDaoImpl {

    public HashMap getNotCourse(String id){
        HashMap<String, Integer> courses = new HashMap<String, Integer> ();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
//        ResultSet rs = DQL.executeQuery(SqlString.selectCourseNameAndScoreSql(id));//先查询已修课程情况
        try {
            conn = JdbcUtil.getConnection();
            stmt = conn.createStatement();
            rs = stmt.executeQuery(SqlString.selectCourseNameAndScoreSql(id));//先查询已修课程情况

            while (rs.next()) {
                String courseName = rs.getString("course_name");
                String score = rs.getString("score");

                if (StudentNotCourseDaoImpl.isnumber(score)) {//成绩为数字
                    int scoreInt = Integer.parseInt(score);
                        courses.put(courseName, 1);
                } else {//成绩为字符串等
                        courses.put(courseName, 1);
                }
            }
            rs = stmt.executeQuery(SqlString.selectCourseName(id));//已知学生学号,查询学生需要选修的课程名称
//            rs = DQL.executeQuery(SqlString.selectCourseName(id));//查询未修课程情况
            while (rs.next()) {
                String courseName = rs.getString("course_name");
                courses.putIfAbsent(courseName, 0);
            }
            HashMap<String, Integer> hashNotMap= new HashMap<String, Integer> ();
            for (Map.Entry<String, Integer> entry : courses.entrySet()) {
                if (entry.getValue() == 0) {//表示该课程没有成绩
                    hashNotMap.put(entry.getKey(), entry.getValue());
                }
            }
            return hashNotMap;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {//回收资源
            JdbcUtil.close(rs,stmt,conn);
        }
        return courses;
    }

    private static boolean isnumber(String num) {
        Pattern pt = Pattern.compile("^[-+]?[\\d]*$");
        return pt.matcher(num).matches();
    }

}
